import matplotlib.pyplot as plt
import numpy as np

resistor=0.1 #ohm
battery_capacity=3.4*3*1000 #mAh
fname = "./data/220902_102817.csv"
data = np.loadtxt(fname, delimiter=",")

def plotdata(data_t,data_c):
    plt.title("current vs. time")
    plt.xlabel("time(s)")
    plt.ylabel("current(mA)")
    plt.ylim(min(data_c),max(data_c)*1.1)
    plt.plot(data_t,data_c)
    plt.show()
    
#calc energy, return mA*s
def calc_energy_consumption(data_t,data_c):
    energy=0
    for i in range(len(data_t)-1):
        energy+=((data_c[i]+data_c[i+1])/2)*(data_t[i+1]-data_t[i])
    return energy

def calc_average_current(data_c):
    sumcurrent=sum(data_c)
    return round(sumcurrent/len(data_c),2)

data_t=data[:,0]
data_c = data[:,1]
plotdata(data_t,data_c)
averagec=calc_average_current(data_c)
print("average current:",averagec,"mA")
print("max current:",max(data_c),"mA")

energy=calc_energy_consumption(data_t,data_c) #mAs
print("energy consumption:",round(energy/3600,4),"mAh")
print("battery capacity:",battery_capacity,"mAh")

timelen=data_t[-1]-data_t[0]
estimated_battery_life=battery_capacity*3600/energy*timelen #s
print("estimated battery life:",round(estimated_battery_life/3600,2),"h ==",round(estimated_battery_life/3600/24,2),"d")